package com.dhruvtaara.beta.action;

import java.util.ArrayList;
import java.util.List;

import com.dhruvtaara.beta.model.entities.User;
import com.dhruvtaara.beta.model.persistance.Datastore;
import com.dhruvtaara.beta.toolset.EmailClient;
import com.dhruvtaara.beta.toolset.PasswordGenerator;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

public class ForgotCredentialAction {

	/**
	 * 
	 * @param emailId
	 * @return
	 * @throws Exception
	 */
	public String generatePassword(String emailId)
			throws PasswordGenerateException {
		String result = null;
		result = PasswordGenerator.generate();		
		return result;
	}

	/**
	 * 
	 * @param newPassword
	 * @param emailId
	 */
	public User updateUser(String newPassword, String emailId) {
		User userInfo = new User();

		DatastoreService datastore = Datastore.get();
		Query query = new Query("User");
		query.addFilter("emailAddress", FilterOperator.EQUAL, emailId);

		final Entity user = datastore.prepare(query).asSingleEntity();

		user.setProperty("password", newPassword);

		userInfo.setFirstName(user.getProperty("firstName").toString());
		userInfo.setLastName(user.getProperty("lastName").toString());

		datastore.put(user);

		return userInfo;
	}

	/**
	 * 
	 * @param emailId
	 * @param newPassword
	 * @param user
	 */
	public void sendEmailNotification(String emailId, String newPassword,
			User user) {
		EmailClient email = new EmailClient();

		StringBuffer message = new StringBuffer();
		message.append(String.format("Dear {0} {1}, <br/>",
				user.getFirstName(), user.getLastName()));
		message.append("Your new password is: ");
		message.append(newPassword);
		message.append("<br/>");
		message.append("Regards, Dhruvtaara team");

		List<String> recipients = new ArrayList<String>();
		recipients.add(emailId);

		email.Send("admin@codeplus.in", "Dhruvtaara Admin", recipients,
				message.toString(), "New Password from Dhruvtaara");
	}
}
